package cn.edu.xmu.orderpayment.order.mq.listener;

import cn.edu.xmu.oomall.core.util.JacksonUtil;
import cn.edu.xmu.oomall.core.util.ReturnObject;
import cn.edu.xmu.orderpayment.order.dao.OrderDao;
import cn.edu.xmu.orderpayment.order.microservice.GoodsService;
import cn.edu.xmu.orderpayment.order.microservice.vo.QuantityVo;
import cn.edu.xmu.orderpayment.order.model.bo.Order;
import cn.edu.xmu.orderpayment.order.model.bo.OrderItem;
import cn.edu.xmu.orderpayment.order.model.po.OrderPo;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
* @Author: Li Yixuan 22920192204232
* @Date: 2021/12/28
*/
@Service
@RocketMQMessageListener(topic = "order-topic2", consumeMode = ConsumeMode.CONCURRENTLY, consumeThreadMax = 10, consumerGroup = "order-group2")
public class OrderListener implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {
    private static final Logger logger = LoggerFactory.getLogger(OrderListener.class);

    @Autowired
    private OrderDao orderDao;


    @Autowired
    private GoodsService goodsService;

    @Override
    public void onMessage(String s) {
        // 消费者获得订单消息，不分单，直接存数据库，支付成功再分单
        logger.info("orderListen:" + s + "time:" + LocalDateTime.now());

        System.out.print("orderListen:" + s + "time:" + LocalDateTime.now());
        Order order = JacksonUtil.toObj(s, Order.class);
        List<OrderItem> orderItemList = order.getOrderItems();
        logger.info(order.getOrderSn()+"开始存数据库");
        if (orderItemList.size() == 1) {
            order.setShopId(orderItemList.get(0).getShopId());
        }
        ReturnObject<OrderPo> ret = orderDao.createOrder(order);
        OrderPo orderPo = ret.getData();
        for (OrderItem item : orderItemList) {
            // 实扣库存
            System.out.println(1);
            goodsService.updateOnsaleQuantity(item.getOnsaleId(),new QuantityVo(Math.toIntExact(-item.getQuantity())));
            item.setOrderId(orderPo.getId());
            orderDao.createOrderItem(item);
        }
    }


    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        logger.info("prepareStart: consumergroup =" + defaultMQPushConsumer.getConsumerGroup());
    }
}
